package org.goyo.main.web.controller.system;

import java.io.File;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.goyo.common.baseBean.AjaxResult;
import org.goyo.common.baseBean.Constants;
import org.goyo.common.utils.StringUtils;
import org.goyo.main.domain.entity.system.FormFile;
import org.goyo.main.services.system.IFormFileService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
/**
 * 文件处理
 * 
 * @author chenchuan
 * 2015年1月27日
 */
@Controller
@RequestMapping("/formFile")
public class FormFileController {
	
	@Resource
	private IFormFileService formFileService;
	/**
	 * 文件上传
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/fileUpload")
	@ResponseBody
	public AjaxResult fileUpload(HttpServletRequest request,@RequestParam MultipartFile[] myfiles, Model model) {

//		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//		MultipartFile files = multipartRequest.getFile("files");
//		List<ConstantsBean> conFile = null;
	    AjaxResult result = null;
		FormFile fileBean = new FormFile();
		MultipartFile multipartFile = myfiles[0];
		String filename = multipartFile.getOriginalFilename();
		String type = filename.substring(filename.lastIndexOf('.') + 1,
				filename.length());
		String id = request.getParameter("formId");
		String formname = request.getParameter("formName");
//		fileBean.setId(StringUtils.getUUID());
		fileBean.setFormName(formname);
		fileBean.setFormId(id);
		fileBean.setClientFileName(filename);
		fileBean.setFileSize(multipartFile.getSize());
		fileBean.setFiletype(type);

		try {
//			conFile = systemService.queryConstantsByCodeType("uploadFile");
			if (multipartFile.getSize() != 0) {
				String fileName = StringUtils.getUUID() + filename;
//				String ctxPath = conFile.get(0).getName();
				File mkdirs = new File(Constants.FILEPATH);
				File file = new File(Constants.FILEPATH + "/" + fileName);
				fileBean.setFilePath(file.getPath());
				if (!mkdirs.exists()) {
					mkdirs.mkdirs();
				}

				fileBean.setServerFileName(fileName);
				multipartFile.transferTo(file);
			}
			formFileService.addFormFile(fileBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		return queryFormFile(request, model);
	    result = AjaxResult.resultSuccess("上传成功", fileBean);
		return result;
	}
}
